/**
 * Created by tdzl2003 on 6/19/16.
 */
import React, { PropTypes } from 'react';

import FormContext from './FormContext';

export default class Form extends React.Component {
  static propTypes = {
    children: PropTypes.element,
    formContext: PropTypes.instanceOf(FormContext),
  };
  static childContextTypes = {
    form: PropTypes.instanceOf(FormContext),
  };

  getChildContext() {
    return {
      form: this.form,
    };
  }

  componentWillMount() {
    [
      'onSubmitBegin',
      'onSubmitEnd',
      'onSubmitResult',
      'onSubmitFail',
    ].forEach(v => {
      const f = this.props[v];
      if (f) {
        this.listeners.push(this.form.addListener(v, f));
      }
    });
  }

  componentWillUnmount() {
    this.listeners.forEach(v => v.remove());
    this.listeners = [];
  }

  getFormContext() {
    return this.form;
  }

  form = this.props.formContext || new FormContext(this.props);
  listeners = [];

  render() {
    return React.Children.only(this.props.children);
  }
}
